package com.zhxh.nzpos.dao;

import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.zhxh.nzpos.db.DBHelper;
import com.zhxh.nzpos.model.Order;

/**
 * Order DAO
 * 
 * @author Administrator
 * 
 */
public class OrderDao {

	DBHelper dbHelper;

	private final static String LOG_TAG = "OrderDao";
	protected static final String TBL_NAME = "buyin_order";

	public OrderDao(Context context) {
		dbHelper = new DBHelper(context);
	}

	/**
	 * add new order
	 * 
	 * @param order
	 */
	public String save(Order order) {
		Log.i(LOG_TAG, "OrderDao  save " + order.toString());
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.beginTransaction();// 开始事务
		try {
			db.execSQL(
					"insert into buyin_order(ID,OrderNumber,TotalCount,HasPayed) values(?,?,?,?)",
					new Object[] { order.getId(), order.getOrderNumber(),
							order.getTotalCount(), order.getHasPayed() });

			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.i("OrderDao  save", e.getMessage());
		}
		db.endTransaction();// 事务结束;
		dbHelper.close();
		return order.getId();
	}

	/**
	 * delete a order by id
	 * 
	 * @param id
	 */
	public void delete(String id) {
		Log.i(LOG_TAG, "OrderDao  delete " + id);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from buyin_order where ID=?", new Object[] { id });
		dbHelper.close();
	}

	/**
	 * delete all
	 * 
	 * @param id
	 */
	public void deleteAll() {
		Log.i(LOG_TAG, "OrderDao  delete all from  order: ");
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from buyin_order");
		dbHelper.close();
	}


	public long getCount() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		long count = DatabaseUtils.queryNumEntries(db, TBL_NAME);
		dbHelper.close();
		return count;
	}
}
